<template>
  <el-dialog 
    v-model="stateDialog.show"
    width="700px"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    append-to-body
    destroy-on-close
    title="设备信息"
  >
    <el-descriptions :column="3" class="first-desc" title="设备属性">
      <el-descriptions-item label="设备自定义名称:" :span="2">{{ stateDialog.row.deviceCustomName }}</el-descriptions-item>
      <el-descriptions-item label="设备DN:">{{ stateDialog.row.deviceName }}</el-descriptions-item>
      <el-descriptions-item v-if="stateDialog.row.locate" label="经纬度:" :span="2">{{ stateDialog.row.locate.longitude }}，{{ stateDialog.row.locate.latitude }}</el-descriptions-item>
      <el-descriptions-item label="设备状态:">
        <el-tag :type="stateDialog.row.online ? 'success' : 'danger'" size="small">
          {{ stateDialog.row.online ? '在线' : '离线' }}
        </el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="设备类型:">{{ getNodeTypeName(stateDialog.row.product) }}</el-descriptions-item>
      <el-descriptions-item label="所属产品:">{{ stateDialog.row.product.name }}</el-descriptions-item>
      <el-descriptions-item v-if="stateDialog.row.group" label="设备分组:">
        <template v-if="Object.keys(stateDialog.row.group).length > 0">
          <el-tag v-for="(group, key) in stateDialog.row.group" :key="key" size="small">{{ group.name }}</el-tag>
        </template>
        <template v-else>
          无
        </template>
      </el-descriptions-item>
      <el-descriptions-item label="电压:">
        <el-button @click="showPropertyHistory('电压')" size="small">历史</el-button>
      </el-descriptions-item>
      <el-descriptions-item label="电流:">
        <el-button @click="showPropertyHistory('电流')" size="small">历史</el-button>
      </el-descriptions-item>
      <el-descriptions-item label="功率:">
        <el-button @click="showPropertyHistory('功率')" size="small">历史</el-button>
      </el-descriptions-item>
    </el-descriptions>
    <el-descriptions v-if="isLightController(stateDialog.row.productKey) || shouldShowJxLoraGateway(stateDialog.row.productKey)" title="控制" style="margin-top: 20px;" />
    <el-form v-if="isLightController(stateDialog.row.productKey)" ref="formRef" label-width="50px">
      <el-form-item label="开关" prop="sw">
        <el-switch v-model="stateDialog.sw" :active-value = "1" :inactive-value = "0" @click="switchChange()" />
      </el-form-item>
      <el-form-item label="调光" prop="sl">
        <el-slider v-model="stateDialog.sl" style="width: 60%;" :max="100" :min="0" @change="percentageChange()" />
      </el-form-item>
    </el-form>
    <jxLoraGateway 
      v-if="shouldShowJxLoraGateway(stateDialog.row.productKey)"
      ref="jx_lora_gatewayRef" 
      :row="stateDialog.row"
    />
  </el-dialog>
  <propertyHistory ref="propertyHistoryRef" />
</template>

<script lang="ts" setup>
import jxLoraGateway from '../../setting/device/components/jxLoraGateway.vue'
import propertyHistory from './propertyHistory.vue'
import { propertySet, getDevicesDetail } from '../api/devices.api'
// 引入公共方法获取设备属性、判断是否为灯控制器
import { getDeviceProperties, isLightController } from '@/utils/deviceUtils'

const emit = defineEmits(['update-icon'])

const stateDialog = reactive({
  show: false,
  row: {} as any,
  sw: 0,
  sl: 0,
  historyTime: [new Date(new Date().getTime() - 24 * 3600 * 1000), new Date(new Date().getTime() + 24 * 3600 * 1000)],
  swName: '',
  slName: '',
  gwmac: '', // 微自然
})

const openDialog = (currentDevice) => {
  stateDialog.show = true
  stateDialog.row = currentDevice
  
  if (isLightController(currentDevice.productKey)){
    const { swName, slName, gwmac } = getDeviceProperties(currentDevice.productKey)
    stateDialog.swName = swName
    stateDialog.slName = slName
    // 单独处理微自然单灯控制器的 gwmac
    stateDialog.gwmac = currentDevice.productKey === 'hATm2Tswh3TDik8W' ? currentDevice.parentId : gwmac

    nextTick(async () => {
      // Object.assign(stateDialog.form, row)
      await Promise.all([sw_sl_property()])
    })
  }
}

// 历史
const propertyHistoryRef = ref()
const showPropertyHistory = (name) => {
  propertyHistoryRef.value.openDialog(name, stateDialog.row)
}

// 开关属性数据
const sw_sl_property = () => {
  getDevicesDetail(stateDialog.row.deviceId)
  .then((res) => {
    stateDialog.sw = Number(res.data.property?.[stateDialog.swName]?.value) || 0
    stateDialog.sl = Number(res.data.property?.[stateDialog.slName]?.value) || 0
  })
}

// 开关按钮
const switchChange = async () => {
  const args: Record<string, any> = {}
  args[stateDialog.swName] = stateDialog.sw
  if (stateDialog.gwmac) {
    args.gwmac = stateDialog.gwmac
  }
  propertySet({
    deviceId: stateDialog.row.deviceId,
    args: args,
  }).then((res) => {
    if (res.code === 200) {
      ElMessage({
        type: 'success',
        message: '开关成功',
      })
      // 更新图标
      emit('update-icon', stateDialog.sw)
    } else {
      ElMessage.error(res.message)
    }
  })
}

// 调光按钮
const percentageChange = async () => {
  const args: Record<string, any> = {}
  args[stateDialog.slName] = stateDialog.sl
  if (stateDialog.gwmac) {
    args.gwmac = stateDialog.gwmac
  }
  propertySet({
    deviceId: stateDialog.row.deviceId,
    args: args,
  }).then((res) => {
    if (res.code === 200) {
      ElMessage({
        type: 'success',
        message: '调光成功',
      })
      // 更新图标
      emit('update-icon', stateDialog.sl == 0 ? 0 : 1)
    } else {
      ElMessage.error(res.message)
    }
  })
}

const shouldShowJxLoraGateway = (productKey: string) => {
  return productKey === 'sfFiZ4Xmd5axJt3Y'
}

// 获取设备类型
const getNodeTypeName = (p) => {
  if (!p) {
    return '直连设备'
  }
  const nodeType = p.nodeType ? p.nodeType : 0
  return ['网关设备', '网关子设备', '直连设备'][nodeType]
}

defineExpose({
  openDialog,
})
</script>

<style lang="scss" scoped>
.first-desc :deep(.el-descriptions__body) {
  padding: 10px 10px 0 10px;
  background-color: #EFEFEF;
}
.el-slider {
  padding: 10px;
}
</style>